package cn.edu.nks.dormitory.student.register.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import cn.edu.nks.dormitory.model.UserInfo;
import cn.edu.nks.dormitory.student.register.db.IDBService;
import cn.edu.nks.dormitory.student.register.dbimpl.DBService;
import cn.edu.nks.util.MD5Utile;

/**
 * 学生注册
 * @author wangbs
 *
 */
public class StudentRegisterAction extends HttpServlet{
	
	private static Logger logger = Logger.getLogger(StudentRegisterAction.class);
	private static final long serialVersionUID = 1L;
	
	private static IDBService idbService = new DBService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/jsons;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		String userName = req.getParameter("userName");
		String passWord = MD5Utile.getMD5(req.getParameter("passWord"));
		
		UserInfo user = new UserInfo();
		user.setUserName(userName);
		user.setUserCode(UUID.randomUUID().toString());
		user.setTime(new Date());
		user.setRoleId(2);//学生角色
		user.setPassWord(passWord);
		
		logger.warn(String.format("register student is %s", user.toString()));
		
	    boolean flag = idbService.addUser(user);//持久化 学生用户
	    //将学生用户 存入学生表  此时只将用户id 对应到学生表即可
	    idbService.relateUserAndStudent(idbService.validateRepeat(userName).getUserId());
	    PrintWriter out = resp.getWriter();
	    JSONObject obj = new JSONObject();
	    if(flag == true){
	    	 obj.put("status", "succ");
	    }else{
	    	obj.put("status", "fail");
	    }
	    out.write(obj.toString());
	}
}
